package com.bayleaf.core;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Logger;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public abstract class BayleafServlet extends HttpServlet{
	
	//리스너 메시지 가져옴
	public String listenerMessage = null;
	//로깅(개발예정)
	private String servletName = null;
	public static BayleafLogger log ;
	//로깅end

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        servletName = getServletName();
//        log = BayleafLogger.init(servletName);
		//로깅때 servletName + 로깅.(통계용)
        listenerMessage = (String)config.getServletContext().getAttribute("listenerMessage");
    }
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException ,IOException {
		
		String jspName = getInitParameter("jsp");
		req.setAttribute("title", getInitParameter("title"));
		forward(jspName,req,res);
	};
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException ,IOException {
		try{
			Model model = new Model(req);
			System.out.println(req.toString());
			String jspName = process(model);
			
			if(jspName == null){
				res.setContentType("text/html;charset=UTF-8");
				PrintWriter pw = res.getWriter();
				pw.write(model.toJson());
				pw.close();
				return;
			}
			
			forward(jspName,req,res);
		}catch(Exception e){
			//에러 핸들링
			req.setAttribute("ErrorMessage", "error occured");
			req.setAttribute("trace", e.getStackTrace());
			forward("/core/Error",req,res);
		}
	};
	
	//@Deprecated
	//public abstract String process(HttpServletRequest req, HttpServletResponse res) throws Exception;
	
	/**
	 * 각 서블릿마다 상속받아 로직을 구현함
	 * @param model
	 * @return
	 * @throws Exception
	 */
	public abstract String process(Model model) throws Exception;
	
	/**
	 * 포워드 메소드
	 * @param jspName
	 * @param req
	 * @param res
	 * @throws IOException
	 * @throws ServletException
	 */
	private void forward(String jspName,HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException{
		RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/jsp"+jspName+".jsp");
		dispatcher.forward(req,res);
	}
	
	/**
	 * 리다이렉션 메소드
	 * @param jspName
	 * @param res
	 * @throws IOException
	 * @throws ServletException
	 */
	private void redirect(String jspName, HttpServletResponse res) throws IOException, ServletException{
		res.sendRedirect("/jsp"+jspName+".jsp");
	}
}
